package com.qfedu.service.impl;

import com.github.pagehelper.PageInfo;
import com.qfedu.dao.EmployeeDao;
import com.qfedu.entity.Employee;
import com.qfedu.service.EmployeeService;
import com.qfedu.util.RandomStringUtil;
import com.qfedu.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * projectName: logistics
 * author: CGY
 * time: 2020/10/9 21:10
 * description:
 */
@Service
public class EmployeeServiceImpl implements EmployeeService {
    @Autowired
    private EmployeeDao employeeDao;

    private String prefix = "ZY";

    private String getCode() {
        String code = null;
        while (true) {
            String s = RandomStringUtil.RandString(6);
            code = prefix + s;
            Employee emp = employeeDao.findByEmployeeCode(code);
            if (emp == null) {
                break;
            }
        }
        return code;
    }

    @Override
    public PageInfo selectAll() {
        List<Employee> list = employeeDao.findAll();
        return new PageInfo(list);
    }

    @Override
    public Result addEmp(Employee employee) {

        String code = getCode();
        employee.setEmployeeCode(code);
        Employee emp = employeeDao.save(employee);
        if (emp == null) {
            return Result.error("添加失败！");
        }
        return Result.success(emp);
    }

    @Override
    public Result selectEmpByCode(String employeeCode) {
        Employee emp = employeeDao.findByEmployeeCode(employeeCode);
        if (emp == null) {
            return Result.error("用户不存在");
        }
        return Result.success(emp);
    }

    @Override
    public Result updateEmp(Employee employee) {
        Employee employee1 = employeeDao.findByEmployeeCode(employee.getEmployeeCode());
        employee.setGender(employee1.getGender());
        Employee emp = employeeDao.save(employee);
        if (emp == null) {
            return Result.error("更新失败");
        }
        return Result.success(emp);
    }
}


